//
//  SplashViewController.m
//  HiMaster3
//
//  Created by jinghao on 16/5/4.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "SplashViewController.h"
#import "PreLoginViewModel.h"
#import "UMSocial.h"
#import "LaunchGifViewone.h"
#import "LaunchGifViewtwo.h"
#import "LaunchGifViewthree.h"
@interface SplashViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong)PreLoginViewModel *viewModel;
@property (nonatomic,weak)IBOutlet UIImageView *splashImageView;
@property (nonatomic,weak)IBOutlet UIView *guidedView;
@property (nonatomic,weak)IBOutlet UIPageControl *pageControl;
@property (nonatomic,weak)IBOutlet UIScrollView *mScrollView;
@property (nonatomic,weak)IBOutlet UIButton *skipButton;
//@property (strong, nonatomic) UIScrollView * mScrollView;
@property (strong, nonatomic) LaunchGifViewone * launchGifViewone;
@property (strong, nonatomic) LaunchGifViewtwo * launchGifViewtwo;
@property (strong, nonatomic) LaunchGifViewthree * launchGifViewthree;

@end

@implementation SplashViewController
@synthesize viewModel = _viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.skipButton.hidden = YES;
    self.view.backgroundColor = AppDefaultColor;
    self.guidedView.hidden = YES;
    self.splashImageView.image = [self getTheLaunchImage];
    [self checkAppVersion];
}
//-(UIScrollView *)mScrollView{
//    if(!_mScrollView){
//        _mScrollView = [[UIScrollView alloc]init];
//        _mScrollView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
//    }
//    return _mScrollView;
//}

- (UIImage *)getTheLaunchImage
{
    NSString *defaultImageName = @"LaunchImage";
    NSInteger osVersion = floor([[[UIDevice currentDevice] systemVersion] floatValue])*100;
    if (osVersion > 800){
        osVersion = 800;
    }
    NSInteger screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    // 3.5inch
    if (screenHeight < 568) {
        // >iOS7
        if (osVersion >= 700) {
            defaultImageName = [NSString stringWithFormat:@"%@-%zd",defaultImageName,osVersion];
        }
        // <iOS7
    }
    // 4.0inch and 4.7inch
    else if(screenHeight < 736){
        // >iOS7
        if (osVersion >= 700) {
            defaultImageName = [NSString stringWithFormat:@"%@-%zd-%zdh",defaultImageName,osVersion,screenHeight];
        }
        // <iOS7
        else {
            defaultImageName = [NSString stringWithFormat:@"%@-%zdh",defaultImageName,screenHeight];
        }
    }
    // 5.5inch
    else{
        NSString *orientation = @"";
        switch ([[UIApplication sharedApplication] statusBarOrientation]) {
            case UIInterfaceOrientationUnknown:
            case UIInterfaceOrientationPortrait:
            case UIInterfaceOrientationPortraitUpsideDown:
                orientation = @"Portrait";
                break;
            case UIInterfaceOrientationLandscapeLeft:
            case UIInterfaceOrientationLandscapeRight:
                orientation = @"Landscape";
                break;
            default:
                break;
        }
        defaultImageName = [NSString stringWithFormat:@"%@-%zd-%@-%zdh",defaultImageName,osVersion,orientation,screenHeight];
    }
    return [UIImage imageNamed:defaultImageName];
}

- (void)checkAppVersion{
    NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
    NSString* appCode = [userDefault objectForKey:FristStartAppVersionKey];
    if (appCode==nil || ![App_Version isEqualToString:appCode])//新版本
    {
        [userDefault setObject: App_Version forKey:FristStartAppVersionKey];
        [userDefault synchronize];
        self.guidedView.hidden = NO;
        [self setUpPage];
    }else{
        [self autoLogin];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(LaunchGifViewone *)launchGifViewone{
    if(!_launchGifViewone){
        NSArray* nibView     = [[NSBundle mainBundle] loadNibNamed:@"LaunchGifViewone" owner:nil options:nil];
        _launchGifViewone       = [nibView objectAtIndex:0];
        _launchGifViewone.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    }
    return _launchGifViewone;
}
-(LaunchGifViewtwo *)launchGifViewtwo{
    if(!_launchGifViewtwo){
        NSArray* nibView        = [[NSBundle mainBundle] loadNibNamed:@"LaunchGifViewtwo" owner:nil options:nil];
        _launchGifViewtwo       = [nibView objectAtIndex:0];
        _launchGifViewtwo.frame = CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeight);
    }
    return _launchGifViewtwo;
}
-(LaunchGifViewthree *)launchGifViewthree{
    if(!_launchGifViewthree){
        NSArray* nibView     = [[NSBundle mainBundle] loadNibNamed:@"LaunchGifViewthree" owner:nil options:nil];
        _launchGifViewthree       = [nibView objectAtIndex:0];
        _launchGifViewthree.frame = CGRectMake(ScreenWidth * 2, 0, ScreenWidth, ScreenHeight);
    }
    return _launchGifViewthree;
}
- (PreLoginViewModel*)viewModel
{
    if (!_viewModel) {
        _viewModel = [[PreLoginViewModel alloc] initWithViewController:self
                      ];
    }
    return _viewModel;
}

- (void)bindViewModel{
    [super bindViewModel];
    self.viewModel.loginSuccessCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        [SharedAppDelegate openAppMainVCT];
        [self.viewModel uploadLogString];
        return [RACSignal empty];
    }];
    self.viewModel.loginErrorCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//        [self.viewModel initAppConfig:2];
        [self hiddenHUDWithString:@"网络原因，自动登录失败" error:NO];
        [SharedAppDelegate openAppMainVCT];
        return [RACSignal empty];
    }];
}
-(void) presentToViewController:(NSString *)identifier{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"LoginTo" bundle:[NSBundle mainBundle]];
    UIViewController *myView = [story instantiateViewControllerWithIdentifier:identifier];
    BaseNavigationController * nav =[[BaseNavigationController alloc]initWithRootViewController:myView];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [[MasterUrlManager shareMasterUrlManager].currentVC presentViewController:nav animated:YES completion:^{
        }];
    });


}

- (void)autoLogin
{
    switch (self.userClient.loginType) {
        case MasterLoginType_Phone:{
            self.viewModel.telePhoneStr = self.userClient.userName;
            self.viewModel.codeStr = self.userClient.password;
            [self.viewModel.autoLoginCommand execute:nil];
        }
            break;
        case MasterLoginType_QQ:{
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:[UMSocialSnsPlatformManager getSnsPlatformString:UMSocialSnsTypeMobileQQ]];
            [[self.viewModel otherLoginCommand] execute:snsAccount];
        }
            break;
        case MasterLoginType_Sina:
        {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:[UMSocialSnsPlatformManager getSnsPlatformString:UMSocialSnsTypeSina]];
            [[self.viewModel otherLoginCommand] execute:snsAccount];
        }            break;
        case MasterLoginType_Weixin:
        {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:[UMSocialSnsPlatformManager getSnsPlatformString:UMSocialSnsTypeWechatSession]];
            [[self.viewModel otherLoginCommand] execute:snsAccount];
        }
            break;
        default:
            sleep(1.0f);
            [SharedAppDelegate openAppMainVCT];
            break;
    }
}

- (void)gotoMainViewController:(id)sender{
    [SharedAppDelegate openAppMainVCT];
}

//改变滚动视图的方法实现
- (void)setUpPage
{
    //设置委托
    self.mScrollView.delegate = self;
    self.mScrollView.bounces= NO;
    //设置背景颜色
//    self.mScrollView.backgroundColor = [UIColor blackColor];
    //设置取消触摸
    self.mScrollView.canCancelContentTouches = NO;
    //设置滚动条类型
    self.mScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否自动裁切超出部分
    self.mScrollView.clipsToBounds = YES;
    //设置是否可以缩放
    self.mScrollView.scrollEnabled = YES;
    //设置是否可以进行画面切换
    self.mScrollView.pagingEnabled = YES;
    //设置在拖拽的时候是否锁定其在水平或者垂直的方向
    self.mScrollView.directionalLockEnabled = NO;
    //隐藏滚动条设置（水平、跟垂直方向）
    self.mScrollView.alwaysBounceHorizontal = NO;
    self.mScrollView.alwaysBounceVertical = NO;
    self.mScrollView.showsHorizontalScrollIndicator = NO;
    self.mScrollView.showsVerticalScrollIndicator = NO;
//    [self.mScrollView addSubview:self.launchGifViewone];
//    [self.mScrollView addSubview:self.launchGifViewtwo];
//    [self.mScrollView addSubview:self.launchGifViewthree];
//    self.mScrollView.contentSize = CGSizeMake(ScreenWidth * 3, ScreenHeight);
//    [self.guidedView addSubview:self.mScrollView];
    
    int imageCount = 3;
    self.pageControl.numberOfPages = imageCount;
    for (int i=0; i<imageCount; i++) {
        NSString *imageName = [NSString stringWithFormat:@"startOneTime%d",i];
        if((int)ScreenHeight % 480==0){
            imageName = [NSString stringWithFormat:@"startOneTime%d-%d",i,i];
        }
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageNamed:imageName];
        imageView.frame = CGRectMake(i*ScreenWidth, 0, ScreenWidth, ScreenHeight);
        
        if (i==(imageCount-1)) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHex:0x21C7B6] forState:UIControlStateNormal];
//            button.backgroundColor = masterDefaultColor;
            button.cornerRadius = 6.0f;
            button.showsTouchWhenHighlighted = NO;
            [button addTarget:self action:@selector(gotoMainViewController:) forControlEvents:UIControlEventTouchUpInside];
            [imageView addSubview:button];
            imageView.userInteractionEnabled = YES;
            button.frame = CGRectMake(75, ScreenHeight-RatioBase6(120), ScreenWidth-RatioBase6(220), 40);
            button.centerX = self.view.centerX;
        }
        NSLog(@"%@",imageView.image);
        [self.mScrollView addSubview:imageView];
    }
    self.mScrollView.contentSize = CGSizeMake(ScreenWidth*imageCount, ScreenHeight);
    
    //设置页码控制器的响应方法
    [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    //设置总页数
    //默认当前页为第一页
    self.pageControl.currentPage = 0;
    //为页码控制器设置标签
    self.pageControl.tag = 110;

}


//改变页码的方法实现
- (void)changePage:(id)sender
{
    //获取当前视图的页码
    CGRect rect = self.mScrollView.frame;
    //设置视图的横坐标，一幅图为320*460，横坐标一次增加或减少320像素
    rect.origin.x = self.pageControl.currentPage * self.mScrollView.frame.size.width;
    //设置视图纵坐标为0
    rect.origin.y = 0;
    //scrollView可视区域
    [self.mScrollView scrollRectToVisible:rect animated:YES];
}
#pragma mark-----UIScrollViewDelegate---------
//实现协议UIScrollViewDelegate的方法，必须实现的
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    if(scrollView.contentOffset.x == ScreenWidth){
//        scrollView.bounces = NO;
//        [self.launchGifViewtwo animationStart];
//    }
//    if(scrollView.contentOffset.x == ScreenWidth * 2){
//        scrollView.bounces = YES;
//        [self.launchGifViewthree animationStart];
//    }
    //获取当前视图的宽度
    CGFloat pageWith = scrollView.frame.size.width;
    //根据scrolView的左右滑动,对pageCotrol的当前指示器进行切换(设置currentPage)
    int page = floor((scrollView.contentOffset.x - pageWith/2)/pageWith)+1;
    //切换改变页码，小圆点
    self.pageControl.currentPage = page;
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView.contentOffset.x > ScreenWidth * 2 ) {
//        [SharedAppDelegate openAppMainVCT];
//    }
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
